package com.qf.xiaomi.web.servlet;

import com.qf.xiaomi.entity.PageBean;
import com.qf.xiaomi.pojo.Goods;
import com.qf.xiaomi.service.GoodsService;
import com.qf.xiaomi.service.impl.GoodsServiceImpl;
import com.qf.xiaomi.web.base.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebServlet("/goodsservlet")
public class GoodsServlet extends BaseServlet {

    GoodsService service = new GoodsServiceImpl();

    /**
     * 根据商品id 查询商品详情
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public String getGoodsById(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        int id = Integer.parseInt(req.getParameter("id"));

        //调用service ，根据id查询商品
        Goods goods = service.findById(id);

        req.setAttribute("goods", goods);

        return "forward:/goodsDetail.jsp";
    }

    /**
     * 根据商品分类id 查询 商品列表（实现分页效果）
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public String getGoodsListByTypeId(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        //获取 分类id
        int typeId = Integer.parseInt(req.getParameter("typeId"));
        //获取 每页条数
        int pageSize = 6;
        String pageSizeStr = req.getParameter("pageSize");
        if(pageSizeStr != null){
            pageSize = Integer.parseInt(pageSizeStr);
        }

        //获取当前页
        int pageNum = 1;
        String pageNumStr = req.getParameter("pageNum");
        if(pageNumStr != null){
            pageNum = Integer.parseInt(pageNumStr);
        }


        //分页查询数据
        PageBean<Goods> pageBean  = service.findGoodsListByTypeIdPage(typeId, pageSize, pageNum);

        //把分页数据存储到请求域
        req.setAttribute("pageBean", pageBean);


        //响应前端
        return "forward:/goodsList.jsp";

    }
}
